import {
    BASE_URL
} from '../../../http/config';
var WxParse = require('../../../wxParse/wxParse.js');

Page({
    data: {
        article: [],
        pageNo: 1,
        totalPageCount: 0,
        isLoading: false,
        articleDetail: {},
        detail: {},
        // img: BASE_URL,
        img:'',
        consultId: null // 新增：用于存储传入的分类ID
    },

    getArticle() {
        if (this.data.isLoading) return;

        this.setData({
            isLoading: true
        });

        wx.showLoading({
            title: '数据正在加载...',
        });

        // 构造请求参数
        const params = {
           
            pageNo: this.data.pageNo,
            pageSize: 10
        };

        // 如果传入了 consultId，则添加到请求参数中
        if (this.data.consultId) {
            params.consultId = this.data.consultId;
        }

        wx.request({
            url: `${BASE_URL}/article/findArticlePage`,
            data: params,
            method: 'GET',
            success: (res) => {
                console.log("文章列表数据：", res.data);

                if (res.data.code === 200) {
                    const newArticles = res.data.data.list || [];
                    // 过滤出 status 为 1 的文章
                    const filteredArticles = newArticles.filter(item => item.status === 1);
                    // 使用过滤后的文章进行格式化
                    const formattedArticles = filteredArticles.map(item => ({
                        ...item,
                        id: item.id,
                        url: item.url || '',
                        articleName: item.articleName || '无标题',
                        articleIntroduction: item.articleIntroduction || '暂无简介'
                    }));

                    this.setData({
                        article: this.data.pageNo === 1 ? formattedArticles : this.data.article.concat(formattedArticles),
                        totalPageCount: res.data.data.totalPageCount || 0
                    });

                    // 增加空数据处理逻辑
                    if (formattedArticles.length === 0 && this.data.pageNo < this.data.totalPageCount) {
                        this.setData({
                            pageNo: this.data.pageNo + 1
                        });
                        this.getArticle();
                    }
                }
                else {
                    wx.showToast({
                        title: res.data.message || '加载失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error("获取文章列表失败：", err);
                wx.showToast({
                    title: '网络错误，加载失败',
                    icon: 'none'
                });
            },
            complete: () => {
                wx.hideLoading();
                wx.stopPullDownRefresh();
                this.setData({
                    isLoading: false
                });
            }
        });
    },

    getArticleDetail(articleId) {
        wx.request({
            url: `${BASE_URL}/article/findById/${articleId}`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    const result = res.data.data;
                    this.setData({
                        articleDetail: result
                    });
                    WxParse.wxParse('detail', 'html', result.content || '', this, 5);
                }
            }
        });
    },

    jumpCourseDetail(e) {
        const courseId = e.currentTarget.dataset.id;

        if (!courseId) {
            wx.showToast({
                title: '课程ID不存在',
                icon: 'none'
            });
            return;
        }

        let readCache = wx.getStorageSync('readCache') || {};

        if (!readCache[courseId]) {
            readCache[courseId] = {
                count: 1,
                timestamp: Date.now()
            };
        } else {
            readCache[courseId].count += 1;
            readCache[courseId].timestamp = Date.now();
        }

        wx.setStorageSync('readCache', readCache);
        console.log(readCache)

        wx.navigateTo({
            url: `/index/pages/articleDetail/articleDetail?id=${courseId}`
        });
    },

    onLoad(options) {
         console.log("接收到的 consultId:", options.consultId);
        // 读取 consultId 参数并存储
        if (options.consultId) {
            this.setData({
                consultId: parseInt(options.consultId) || null
            });
        }

        this.getArticle();
    },

    onReady() {},

    onShow() {},

    onHide() {
        // this.reportReadDataToBackend();
    },

    onUnload() {},

    onPullDownRefresh() {
        this.setData({
            article: [],
            pageNo: 1,
            totalPageCount: 0
        });
        this.getArticle();
    },

    onReachBottom() {
        if (this.data.pageNo >= this.data.totalPageCount) {
            wx.showToast({
                title: '没有更多数据了',
                icon: 'none'
            });
            return;
        }
        this.setData({
            pageNo: this.data.pageNo + 1
        });
        this.getArticle();
    },

    onShareAppMessage() {
        return {
            title: '文章列表',
            path: '/index/pages/articleList/articleList'
        };
    },

    reportReadDataToBackend() {
        const readCache = wx.getStorageSync('readCache') || {};

        const readList = Object.keys(readCache).map(id => ({
            id: parseInt(id),
            count: readCache[id].count
        }));

        if (readList.length === 0) return;

        wx.request({
            url: `${BASE_URL}/article/read/batch`,
            method: 'POST',
            data: readList,
            header: {
                'Content-Type': 'application/json'
            },
            success: (res) => {
                console.log("阅读量上报结果：", res.data);
                if (res.data.code === 200) {
                    wx.removeStorageSync('readCache');
                }
            },
            fail: (err) => {
                console.error("上报失败：", err);
            }
        });
    }
});
